package top.ijiujiu.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import top.ijiujiu.entity.SysUser;
import top.ijiujiu.util.JwtTokenUtil;
import top.ijiujiu.util.ResultUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理登录验证成功的类
 *
 * @Author 神秘的黄瓜
 * @Version 1.0
 * @Date 2020-04-01 11:46
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(AuthenticationSuccessHandlerImpl.class);

    /**
     * Json转化工具
     */
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @SuppressWarnings("deprecation")
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        SysUser user = (SysUser) authentication.getPrincipal();
        LOGGER.info("登录用户为:{}", user.getUsername());
        String token = JwtTokenUtil.generateToken(user);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setHeader(JwtTokenUtil.TOKEN_HEADER, JwtTokenUtil.TOKEN_PREFIX + token);
        ResultUtil<SysUser> result = new ResultUtil<>();
        result.success("登录成功", user);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
